import { Modal, Form, Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadDataset } from '@/api/sr-stms';
import { useLoading } from '@/hooks/baseHook';

interface UploadModalPrps {
  visible: boolean;
  onCancel?: () => void;
  callback?: () => void;
  record: any;
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const UploadModal = (props: UploadModalPrps) => {
  const { visible, onCancel, callback, record } = props;
  const [form] = Form.useForm();
  const [loading, load] = useLoading();

  const handleCancel = () => {
    if (onCancel) {
      form.resetFields();
      onCancel();
    }
  };

  const handleOk = async () => {
    const vals = await form.validateFields();
    const formData = new FormData();
    vals.images.forEach((item: { originFileObj: string | Blob }) => {
      formData.append('images', item.originFileObj);
    });
    vals.labels.forEach((item: { originFileObj: string | Blob }) => {
      formData.append('labels', item.originFileObj);
    });

    await load(uploadDataset(record.id)(formData));
    message.success('上传成功！');
    callback && callback();
    handleCancel();
  };

  const normFile = (e: any) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  return (
    <Modal
      width={500}
      title={'上传数据集'}
      visible={visible}
      onCancel={handleCancel}
      onOk={handleOk}
      okButtonProps={{ loading: loading }}
      okText="提交"
    >
      <Form {...layout} form={form}>
        <Form.Item
          name="images"
          label="图片文件"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[{ required: true, message: '请上传图片文件夹' }]}
        >
          <Upload beforeUpload={() => false} directory>
            <Button icon={<UploadOutlined />}>点击上传文件夹</Button>
          </Upload>
        </Form.Item>

        <Form.Item
          name="labels"
          label="标签文件"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[{ required: true, message: '请上传标签文件夹' }]}
        >
          <Upload beforeUpload={() => false} directory>
            <Button icon={<UploadOutlined />}>点击上传文件夹</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UploadModal;
